package util;

import lombok.SneakyThrows;

import java.sql.*;
import java.util.Objects;

/**
 * @classname:DBHelper
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/28 17:07
 * @version: 0.1
 * @since:1.8
 */
public class DBHelper {
    private DBHelper() {
    }

    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal() {
        @Override
        @SneakyThrows
        protected Object initialValue() {
            return DriverManager.getConnection(PropUtil.getValue("url"), PropUtil.getValue("password"), PropUtil.getValue("username"));
        }
    };

    public static Connection getCon() {
        return THREAD_LOCAL.get();
    }


    public static void closeResources(Connection connection,PreparedStatement ps,ResultSet rs) {
        Objects.requireNonNull(connection);
        Objects.requireNonNull(ps);
        Objects.requireNonNull(rs);
        try {
            rs.close();
            ps.close();
            connection.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResources(Connection connection,PreparedStatement ps) {
        Objects.requireNonNull(connection);
        Objects.requireNonNull(ps);
        try {
            ps.close();
            connection.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void closeResources(Connection connection) {
        Objects.requireNonNull(connection);
        try {
            connection.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }



}
